import React, { useState, useEffect } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { useIntl, connect } from 'umi';
import {
  Card,
  Popconfirm,
  Divider,
  Tag,
  Tabs,
  Badge,
  Image,
  Space,
  Button,
  Input,
  Table,
  Drawer,
  Checkbox,
  DatePicker,
} from 'antd';
import { PlusOutlined, SyncOutlined, ExportOutlined } from '@ant-design/icons';
import moment from 'moment';
import EventEdit from './components/eventEdit';
import request from '@/utils/request';
import UploadUtil from '@/components/UploadUtil';

const { Search } = Input;
const { TabPane } = Tabs;
const { RangePicker } = DatePicker;
const apiURL = '/api/services/app/EventDetail/';

const ViewPage: React.FC<any> = (props) => {
  const intl = useIntl();
  const [loading, setLoading] = useState(false);
  const [dataSource, setDataSource] = useState([]);
  const [visible, setVisible] = useState(false);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [pageIndex, setPageIndex] = useState(1);
  const [pageSize] = useState(10);
  const [totalCount, setTotalCount] = useState(0);
  const [record, setRecord] = useState({});
  const [payload, setPayload] = useState({ keywords: '', status: '' });
  const [daterange, setDaterange] = useState<any>({});
  const [loading2, setLoading2] = useState(false);
  const [countWait, setCountWait] = useState(0);
  const [countAprv, setCountAprv] = useState(0);
  const [countOver, setCountOver] = useState(0);
  const [countTotal, setCountTotal] = useState(0);

  useEffect(() => {
    fetchDatas();
    request(apiURL + 'GetList', {
      method: 'Get',
      params: { SkipCount: 0, MaxResultCount: 0 },
    }).then((response) => {
      const resp = response.result;
      if (resp?.items) {
        setCountWait(resp.items.filter((o: any) => o.eventStatus === 'pending').length);
        setCountAprv(resp.items.filter((o: any) => o.eventStatus === 'approved').length);
        setCountOver(resp.items.filter((o: any) => o.eventStatus === 'completed').length);
        setCountTotal(resp.totalCount);
      }
    });
  }, []);

  useEffect(() => {
    fetchDatas();
  }, [payload, pageIndex]);

  const fetchDatas = () => {
    setLoading(true);
    const stime = daterange ? daterange[0]?.format('YYYY-MM-DD') : '';
    const etime = daterange ? daterange[1]?.format('YYYY-MM-DD') : '';
    request(apiURL + 'GetList', {
      method: 'GET',
      params: {
        SkipCount: (pageIndex - 1) * pageSize,
        MaxResultCount: pageSize,
        ...payload,
        stime,
        etime,
      },
    }).then((resp) => {
      if (resp) {
        setDataSource(resp.result?.items);
        setTotalCount(resp.result?.totalCount);
        setLoading(false);
      }
    });
  };

  const onSelectChange = (selectedRowKeys: any) => {
    setSelectedRowKeys(selectedRowKeys);
  };

  const handleDelete = (id: any) => {
    request(apiURL + 'Delete', {
      method: 'DELETE',
      params: { id },
    }).then(() => {
      fetchDatas();
    });
  };

  const switchModal = (visible: boolean, record: any = null) => {
    setVisible(visible);
    setRecord(record);
  };

  const onSearch = (value: string) => {
    setPayload({ ...payload, keywords: value });
  };

  const callback = (key: string) => {
    setPayload({ ...payload, status: key === 'all' ? '' : key });
    setPageIndex(1);
  };

  const handlerExport = async () => {
    const stime = daterange ? daterange[0]?.format('YYYY-MM-DD') : '';
    const etime = daterange ? daterange[1]?.format('YYYY-MM-DD') : '';
    setLoading2(true);
    const resp = await request('/api/Excel/ExportEvent', {
      method: 'POST',
      params: { ...payload, stime, etime },
      responseType: 'blob',
    });

    const url = window.URL.createObjectURL(resp);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'EventTask.xls';
    a.click();
    setLoading2(false);
  };

  const columns = [
    {
      title: intl.formatMessage({ id: 'pages.eventNumber' }),
      dataIndex: 'eventNumber',
    },
    {
      title: intl.formatMessage({ id: 'pages.event' }),
      render: (_record: any) => {
        const srcPc =
          UploadUtil.ossServ + (_record.problemPic ? _record.problemPic.split(',')[0] : '');

        return (
          <Image
            width={60}
            height={40}
            src={srcPc + '?x-oss-process=image/resize,m_fill,h_60'}
            preview={{
              src: srcPc,
            }}
          />
        );
      },
    },
    {
      title: intl.formatMessage({ id: 'pages.type' }),
      dataIndex: 'eventType',
    },
    {
      title: intl.formatMessage({ id: 'pages.status' }),
      dataIndex: 'eventStatus',
      render: (text: any) => (
        <Tag color={text === 'padding' ? 'red' : text === 'completed' ? 'green' : 'blue'}>{text}</Tag>
      ),
    },
    {
      title: intl.formatMessage({ id: 'pages.rectification' }),
      dataIndex: 'rectification',
      render: (text: boolean) => <Checkbox checked={text} />,
    },
    {
      title: intl.formatMessage({ id: 'pages.creationTime' }),
      dataIndex: 'creationTime',
      render: (text: any) => <span>{moment(text).format('YYYY-MM-DD hh:mm:ss')}</span>,
    },
    {
      title: intl.formatMessage({ id: 'pages.overTime' }),
      dataIndex: 'overTime',
      render: (text: any) => (
        <span>{text ? moment(text).format('YYYY-MM-DD hh:mm:ss') : ''}</span>
      ),
    },
    {
      title: intl.formatMessage({ id: 'pages.operation' }),
      render: (_record: any) =>
        dataSource.length >= 1 ? (
          <span>
            <Popconfirm title={intl.formatMessage({ id: 'pages.delete?' })} onConfirm={() => handleDelete(_record.id)}>
              <a>{intl.formatMessage({ id: 'pages.delete' })}</a>
            </Popconfirm>
            <Divider type="vertical" />
            <a onClick={() => switchModal(true, _record)}>{intl.formatMessage({ id: 'pages.edit' })}</a>
          </span>
        ) : null,
    },
  ];

  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };

  const hasSelected = selectedRowKeys.length > 0;

  return (
    <PageHeaderWrapper title={false} breadcrumbRender={false} ghost>
      <Card>
        <Space>
          <Button
            type="primary"
            onClick={fetchDatas}
            loading={loading}
            icon={<SyncOutlined />}
          >
            {intl.formatMessage({ id: 'pages.refresh' })}
          </Button>
          <Button type="primary" onClick={() => switchModal(true)} icon={<PlusOutlined />}>
            {intl.formatMessage({ id: 'pages.add' })}
          </Button>
          <Button
            type="default"
            onClick={handlerExport}
            icon={<ExportOutlined />}
            loading={loading2}
          >
            {intl.formatMessage({ id: 'pages.export' })}
          </Button>
          <RangePicker onChange={(e) => setDaterange(e)} />
          <Search
            style={{ width: 240 }}
            placeholder={intl.formatMessage({ id: 'pages.enterKeywords' })}
            onSearch={onSearch}
          />
          <span>{hasSelected ? intl.formatMessage({ id: 'pages.selected' }, { count: selectedRowKeys.length }) : ''}</span>
        </Space>
        <Tabs defaultActiveKey="1" onChange={callback}>
          <TabPane tab={<span>{intl.formatMessage({ id: 'pages.all' }, { count: countTotal })}</span>} key="all" />
          <TabPane tab={<Badge count={countWait}>{intl.formatMessage({ id: 'pages.pending' })}</Badge>} key="pending" />
          <TabPane tab={<Badge count={countAprv}>{intl.formatMessage({ id: 'pages.approved' })}</Badge>} key="approved" />
          <TabPane tab={<span>{intl.formatMessage({ id: 'pages.completed' }, { count: countOver })}</span>} key="completed" />
        </Tabs>
        <Table
          rowKey="id"
          loading={loading}
          rowSelection={rowSelection}
          columns={columns}
          dataSource={dataSource}
          pagination={{
            onChange: (page: number) => {
              setPageIndex(page);
              fetchDatas();
            },
            pageSize,
            total: totalCount,
          }}
        />
      </Card>
      <Drawer
        title={intl.formatMessage({ id: 'pages.editCase' })}
        placement="right"
        visible={visible}
        destroyOnClose={true}
        onClose={() => switchModal(false)}
        width={600}
      >
        <EventEdit
          record={record}
          fetchDatas={fetchDatas}
          closeDraw={() => switchModal(false)}
        />
      </Drawer>
    </PageHeaderWrapper>
  );
};

export default connect(({ user }: API.IConnectState) => ({
  currentUser: user.currentUser,
}))(ViewPage);
